<template lang='pug'>
  .monitor-wrap
    ArcgisMap.monitor-map(
      ref="monitorMap"
      v-if="areas.length"
      v-model="markersOject"
      :mapOptions="mapOptions"
      :markers="activeMarkers"
      :areas="areas"
      :buildings="buildings"
      :pipelines="pipelines"
      :dmaAreas="dmaAreas"
      :areaInfo="areaInfo"
      @receiveAreaId="receiveAreaId"
      @selectMarker="selectMarker"
      @setMarkerContent="setMarkerContent"
      @openMap="openMap"
      @saveMarkersObject="saveMarkersObject"
      @getAreaInfowindows="getAreaInfowindows"
      @mapClick="mapClick")
      MonitorTableToolbar.monitor-table-toolbar(
        v-if="fullMap"
        :activeToolbar="activeToolbar"
        @changeToolbar="changeToolbar")
      MonitorTable.monitor-table(
        v-if="fullMap"
        v-show="activeToolbar==='table'")
</template>

<script>
/**
 * @name Monitor 分区监控
 * @author caixq <caixq@gddxit.com>
 * @description 分区监控主页面
 */
import { keyBy } from 'lodash'
import { deviceType, floatingWindow, areaInfoMesg } from '../../config/marker'
import ArcgisMap from './Waterworks'
import MonitorTableToolbar from './TableToolbar'
import MonitorTable from './MonitorTable/Table'
// --
import Layout from '@/containers/Common/Layout'
import arcgisdemo from './arcgisdemo'
import demoPng from '../../assets/img/NormalP.png'
export default {
  name: 'Monitor',
  components: {
    ArcgisMap,
    MonitorTableToolbar,
    MonitorTable,
    Layout
  },
  data () {
    return {
      // 初始创建地图的配置项
      mapOptions: {
        basemap: "gray-vector",
        logo: false,
        slider: false,
        // center: [84.873946, 45.595886],
        center: [0, 0],
        zoom: 16
      },
      // 建筑
      buildings: [],
      // 管线
      pipelines: [],
      // 定位点列表
      markers: [],
      // 最新分区信息
      areas: [],
      // dma分区信息
      dmaAreas: [],
      // 分区数量
      areaCount: 0,
      isloaded: false,
      // 定位点筛选条件
      filterDeviceList: [],
      filterFacturerList: [],
      filterCaliberList: [],
      // 报警框筛选条件
      policeFlag: [],
      filterPoliceList: [],
      // 侧边栏工具切换条件
      activeToolbar: '',
      // 设备弹窗信息
      stage: [],
      deviceStatList: [],
      // Gis工具
      activeGis: '',
      // 分区预警信息
      areasWarn: [],
      // 分区统计信息
      areaInfo: {},
      fullMap: true, // 地图撑满状态标记
      areaId: Number,
      // 是否展开悬浮窗
      isExpand: false,
      // 保存悬浮窗的数据来源
      markerE: {},
      // 保存设备点对象实例
      markersOject: {},
      // 控制搜索框的列表显示
      showSearchBarList: true,

      // 地图的数据集合,
      mapData: [],
      // 地图的相对坐标
      minx: {},
      miny: {},
    }
  },
  computed: {
    // 监听定位点的变化
    // TODO: 完成口径筛选功能 口径筛选只作用于流量计和阀门
    activeMarkers () {
      // return this.markers.filter(marker => {
      //   return this.filterDeviceList.includes(marker.data.device.deviceName) && (marker.data.device.diameter === null ? true : (this.filterCaliberList.includes(marker.data.device.diameter))) && (!this.filterPoliceList.length || this.filterPoliceList.includes(marker.data.policeFlag))
      // })
      return this.markers;
    }

  },
  watch: {
    isExpand (data) {
      let expand = document.getElementsByClassName('contentPane')[0]
      expand.setAttribute('class', data ? 'contentPane expand' : 'contentPane')
    }
  },
  mounted () {
    console.log("~~~~~~~" + this.$route.query.id)
    this.initMapData()
    // this.getMarkers()
    this.getAreaMesg()
    // this.getDMAMesg()
    // this.getDeviceStatistical()
  },
  methods: {
    // 初始化地图展示的数据
    initMapData () {
      let minx = Number.MAX_VALUE;
      let miny = Number.MAX_VALUE;
      let tempBuildings = arcgisdemo['layers'][0].featureSet.features
        .map( value => ({
          x: value.geometry.x,
          y: value.geometry.y,
          paths: value.geometry.paths,
          spatialReference: value.geometry.spatialReference,
          name: value.attributes.NAME,
          type: value.attributes.Type,
          data: value
        }))
      tempBuildings.forEach( ({x, y}) => {
        minx = minx < x ? minx : x;
        miny = miny < y ? miny : y;
      })
      this.buildings = tempBuildings.map( value => ({
        ...value,
        position: [
          (value.x - minx),
          (value.y - miny)
        ],
        symbol: [demoPng, 31, 40]
      }));

      let width = 0;
      let height = 0;
      // let mapSpatialReference = undefined;
      this.buildings.forEach( ({position, spatialReference}) => {
        width = width > position[0] ? width : position[0];
        height = height > position[1] ? height : position[1];
        // mapSpatialReference = mapSpatialReference || spatialReference;
      })
      // this.mapOptions.center[0] = width / 2;
      // this.mapOptions.center[1] = height / 2;
      // this.mapOptions.spatialReference = mapSpatialReference;

      this.buildings.forEach( ({position}) => {
        position[0] = position[0] - (width / 2);
        position[1] = position[1] - (height / 2);
      })


      this.pipelines = arcgisdemo['layers'][1].featureSet.features
        .map( value => ({
          paths: value.geometry.paths,
          spatialReference: value.geometry.spatialReference,
          name: value.attributes.NAME,
          data: value
        }))
      this.pipelines.forEach( ({paths}) => {
        let tempPath = paths[0];

        tempPath.forEach( (path) => {
            path[0] = (path[0] - minx) - (width / 2);
            path[1] = (path[1] - miny) - (height / 2);
          }
        );
      });
    },

    // get定位点数据
    getMarkers () {
      this.$get({
        url: 'pn/monitor/device/onlineData?deviceName=LUF,DMA,DPAF,PT'
      }).then(({data}) => {
        if (data) {
          this.markers = data.map(item => {
            return {
              data: item,
              position: [item.longitude, item.latitude],
              symbol: [deviceType[item.deviceName].icon[item.policeFlag], 31, 40]
            }
          })
        }
      })
    },
    // get分区统计信息
    getAreaMesg () {
      this.$get({
        url: 'pn/dpa/monitor/onlineData'
      }).then(({ areas, areaInfo }) => {
        // this.areas = areas
        this.areas = areas.map(item => {
          return {
            ...item,
            rings: item.ranges
          }
        })
        if (areaInfo.length) {
          this.areaInfo = keyBy(areaInfo, 'id')
          this.areasWarn = areas.map(area => {
            return {
              name: area.name,
              color: area.color,
              status: this.areaInfo[area.id].status
            }
          })
        }
      })
    },
    // get dma分区信息
    getDMAMesg () {
      this.$get({
        url: 'dma/dmaMeterInfo/getMapData'
      }).then((res) => {
        if (res) {
          this.dmaAreas = res.data.map(area => {
            return {
              name: area.areaName,
              // FIXME: 颜色缺少字段，后端跟进后修改
              color: '#000',
              rings: area.areaBounds,
              areaCenter: area.areaCenter
            }
          })
        }
      })
    },
    // get报警数据及设备数据
    getDeviceStatistical () {
      this.$get({
        url: 'pn/monitor/device/stat?deviceName=LUF,DMA,DPAF,PT'
      }).then((res) => {
        this.areaCount = res.areaCount
        this.stage = res.stage
        this.policeFlag = res.policeFlag
        this.deviceStatList = res.deviceName
      })
    },
    // 接收分区id，处理点击事件
    receiveAreaId (e) {
      this.areaId = e.id
      this.fullMap = false
      this.$emit('changeAreaId', this.areaId)
      this.$emit('changeFullMap', this.fullMap)
    },
    // 双击打开地图事件
    openMap (e) {
      this.fullMap = true
      this.$emit('openMap')
    },
    // 定位点筛选条件
    monitorMarkersFilter (filterBy, data) {
      if (filterBy === 'deviceTypeList') {
        this.filterDeviceList = data
      } else if (filterBy === 'caliberList') {
        this.filterCaliberList = [...data, 0]
      } else if (filterBy === 'parameterList') {
        this.$refs.monitorMap.changeLayer(data, 'graphicsLayerIds')
      } else if (filterBy === 'gisList') {
        // console.log(data)
        this.$refs.monitorMap.changeGLLayer(data)
      }
    },
    // 报警筛选
    monitorMarkersPolice (policeFlag) {
      if (this.filterPoliceList.includes(policeFlag.label)) {
        this.filterPoliceList = []
      } else {
        this.filterPoliceList = [policeFlag.label]
      }
    },
    // 侧边栏控件切换
    changeToolbar (toolbar) {
      console.log('outset change toolbar')
      this.activeToolbar = toolbar
      // this.activeGis = ''
      // this.$refs.map.cancleDraw()
    },
    // Gis工具处理
    monitorMapGis ({name, label}) {
      this.activeGis = name
      // this.$refs.map.gisSelect(label)
    },
    // 调整地图的缩放比例并回归到中心点
    returnToMap () {
      this.$refs.monitorMap.returnToMap()
    },
    // 增大或减小地图的缩放级别
    setZoom (zoom) {
      this.$refs.monitorMap.setZoom(zoom)
    },
    selectSearch (position, value) {
      this.filterDeviceList = Array.from(new Set(this.filterDeviceList.concat(value.deviceName)))
      this.$refs.monitorMap.selectMarker(position, 16)
      this.$refs.monitorMap.setSymbolSize(this.markersOject[value.id], 38, 47)
    },
    // 切换图层
    changeLayer (layer) {
      this.$refs.monitorMap.changeLayer([layer.value, 'layerN'], 'layerIds')
    },
    // 选择设备查看历史数据
    selectMarker (data) {
      this.fullMap = false
      this.$emit('selectMarker', data)
      this.$emit('changeFullMap', this.fullMap)
      this.showSearchBarList = !this.showSearchBarList
    },
    saveMarkersObject (markersObject) {
      this.markersOject = markersObject
    },
    // 地图点击事件
    mapClick () {
      this.activeToolbar = ''
    },
    setMarkerContent (e) {
      let expand = document.getElementsByClassName('contentPane')[0]
      expand.setAttribute('class', 'contentPane')
      this.markerE = e
      let code
      let { policeFlag, siteName, deviceName, address, recordTime, data } = e.graphic.attributes
      const siteCode = {
        label: '站点编号',
        value: e.graphic.attributes.siteCode
        // unit: ''
      }
      const deviceCode = {
        label: '用户编号',
        value: e.graphic.attributes.userCode
        // unit: ''
      }
      if (deviceName === 'LUF' || deviceName === 'DMA') {
        code = deviceCode
      } else {
        code = siteCode
      }
      let title = siteName === null ? '-' : siteName
      let target = ''
      let targetList = keyBy(data, 'targetId')
      let policeFlagList = {
        normal: {
          label: '绿色正常'
        },
        complete: {
          label: '蓝色关注'
        },
        warning: {
          label: '黄色预警'
        },
        danger: {
          label: '红色报警'
        }
      }
      targetList.policeFlag = { label: '状态', value: policeFlagList[policeFlag.toLowerCase()].label, unit: '' }
      floatingWindow[deviceName].map((item, index) => {
        target += `<div class="${index >= 3 ? 'expandTarget' : ''}"><span class="area-mesg"}>${targetList[item].label}</span>：<span class="${policeFlag.toLowerCase()}" style="font-weight:bolder">${targetList[item].value ? targetList[item].value : '-'}</span> ${targetList[item].unit}</div>`
      })
      let content = `<div class="marker-name">${deviceType[deviceName].label ? deviceType[deviceName].label : '-'}</div>
                     <div class="marker-address">${address !== null ? address : '-'}</div>
                     <hr class="marker-hr">
                     <div><span class="area-mesg">采集时间</span>: ${recordTime ? this.$moment(recordTime).format('YYYY-MM-DD HH:mm:ss') : '-'}</div>
                     <div><span class="area-mesg">${code.label}</span>: ${code.value ? code.value : '-'}</div>
                     ${target}
                     <div class="triangle">
                      <span class="triangle-item iconfont icon-angle-down"></span>
                      <span class="triangle-item iconfont icon-angle-down toggle-bottom"></span>
                     </div>`
      this.$refs.monitorMap.setInfowindow(title, content, policeFlag.toLowerCase())
      this.toggle()
    },
    getAreaInfowindows (e) {
      // FIXME: 移入name图像中存在问题！！！！
      let { name, id } = e.graphic.attributes
      let { recordTime, dws, lucw, avgPressure, nrw, nrwRate, status } = this.areaInfo[id]
      // 创建infowindow的窗体内容DOM
      let content = `<div><span class="area-mesg">${areaInfoMesg['recordTime'].label}</span>: ${recordTime ? this.$moment(recordTime).format('YYYY-MM-DD HH:mm:ss') : '-'}</div>
                     <div><span class="area-mesg">${areaInfoMesg['dws'].label}</span>: ${dws.toFixed(3)} m³/h</div>
                     <div><span class="area-mesg">${areaInfoMesg['lucw'].label}</span>: ${lucw.toFixed(3)} m³/h</div>
                     <div><span class="area-mesg">${areaInfoMesg['avgPressure'].label}</span>: ${avgPressure.toFixed(3)} m</div>
                     <div><span class="area-mesg">${areaInfoMesg['nrw'].label}</span>: ${nrw.toFixed(3)} m³/h</div>
                     <div><span class="area-mesg">${areaInfoMesg['nrwRate'].label}</span>: <span class="${status.toLowerCase()}">${nrwRate.toFixed(3)} %</span></div>`
      this.$refs.monitorMap.setInfowindow(name, content, status.toLowerCase())
    },
    toggle () {
      let toggle = document.getElementsByClassName('triangle')[0]
      let triangleItem = document.getElementsByClassName('triangle-item')
      toggle.addEventListener('click', e => {
        this.isExpand = !this.isExpand
        if (this.isExpand) {
          triangleItem[0].setAttribute('class', 'triangle-item iconfont icon-angle-up')
          triangleItem[1].setAttribute('class', 'triangle-item iconfont icon-angle-up toggle-bottom')
        } else {
          triangleItem[0].setAttribute('class', 'triangle-item iconfont icon-angle-down')
          triangleItem[1].setAttribute('class', 'triangle-item iconfont icon-angle-down toggle-bottom')
        }
      })
    }
  }
}
</script>

<style lang='sass' scoped>
@mixin position($right, $bottom)
  position: absolute
  right: $right
  bottom: $bottom
  z-index: 2
.monitor-wrap
  display: flex
  width: 100%
  height: 100%
  .monitor-map
    flex: 1
    position: relative
    .monitor-map-searchbar
      position: absolute
      left: 30px
      top: 20px
      z-index: 2
    .monitor-map-areasboard
      position: absolute
      left: 30px
      bottom: 20px
      z-index: 2
    .monitor-map-police
      position: absolute
      top: 20px
      left: 50%
      transform: translateX(-50%)
      z-index: 2
    .monitor-table-toolbar
      position: absolute
      left: 30px
      bottom: 30px
      z-index: 20
    .monitor-map-toolbar
      @include position(20px, 50%)
    .monitor-map-stat
      @include position(72px, 45%)
    .monitor-map-gis
      @include position(72px, 50%)
    .monitor-map-toolbox
      @include position(20px, 30px)
    .monitor-map-filter
      @include position(72px, 40px)
</style>
